package com.guomei.service.curse.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.curse.Coupon;
import com.guomei.bean.curse.Course;
import com.guomei.bean.curse.UserCoupon;
import com.guomei.mapper.curse.CouponMapper;
import com.guomei.mapper.curse.CourseMapper;
import com.guomei.mapper.curse.UserCouponMapper;
import com.guomei.service.curse.CouponService;
import com.guomei.service.curse.UserCouponService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户优惠券服务实现类
 */
@Service
@Slf4j
@Transactional
public class UserCouponServiceImpl implements UserCouponService {
    @Resource
    private UserCouponMapper userCouponMapper;

    @Resource
    private CouponService couponService;

    @Resource
    private CouponMapper couponMapper;
    @Resource
    private CourseMapper courseMapper;

    @Override
    public UserCoupon getById(Long id) {
        if (id == null) {
            return null;
        }
        return userCouponMapper.selectById(id);
    }

    @Override
    public UserCoupon getByUserIdAndCouponId(Long userId, Long couponId) {
        if (userId == null || couponId == null) {
            return null;
        }
        return userCouponMapper.selectByUserIdAndCouponId(userId, couponId);
    }

    @Override
    public Result<?> getByUserId(UserCoupon userCoupon) {
        if (userCoupon.getUserId() == null) {
            return Result.fail("用户ID不能为空");
        }
        PageHelper.startPage(userCoupon.getPageNum(), userCoupon.getPageSize());
        List<UserCoupon> userCoupons = userCouponMapper.selectByUserId(userCoupon.getUserId(), userCoupon.getStatus());
        for (UserCoupon coupon : userCoupons) {
            Coupon coupon1 = couponMapper.selectById(coupon.getCouponId());
            coupon.setCoupon(coupon1);
        }
        // 封装分页结果到PageData
        PageData<UserCoupon> pageData = new PageData<>();
        PageInfo<UserCoupon> pageInfo = new PageInfo<>(userCoupons);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(userCoupon.getPageNum());
        pageData.setPageSize(userCoupon.getPageSize());
        return Result.success(pageData);
    }

    @Override
    public UserCoupon getByOrderNo(String orderNo) {
        if (orderNo == null || orderNo.trim().isEmpty()) {
            return null;
        }
        return userCouponMapper.selectByOrderNo(orderNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> receiveCoupon(Long userId, Long couponId) {

        // 检查用户是否已领取该优惠券
        UserCoupon existCoupon = getByUserIdAndCouponId(userId, couponId);
        if (existCoupon != null) {
            log.info("用户已领取该优惠券");
            return Result.fail("用户已领取该优惠券");
        }

        // 检查优惠券是否存在且有效
        Coupon coupon = couponService.getById(couponId);
        if (coupon == null || coupon.getStatus() != 1
//                || coupon.getStartTime().isAfter(LocalDateTime.now())
//                || coupon.getEndTime().isBefore(
//                        LocalDateTime.now())
        ) {
            log.info("优惠券不存在或已失效");
            return Result.fail("优惠券不存在或已失效");
        }

        // 检查优惠券剩余数量
        if (coupon.getTotalCount() != null && coupon.getUsedCount() >= coupon.getTotalCount()) {
            log.info("优惠券已用完");
            return Result.fail("优惠券已用完");
        }

        // 创建用户优惠券记录
        LocalDateTime now = LocalDateTime.now();
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(couponId);
        userCoupon.setGetTime(now);
        userCoupon.setStatus((short) 1); // 未使用
        userCoupon.setCreatedTime(now);
        userCoupon.setUpdatedTime(now);

        // 保存记录并更新优惠券使用数量
        if (userCouponMapper.insert(userCoupon) > 0) {
            couponService.incrementUsedCount(couponId);
            log.info("领取成功");
            return Result.success("领取成功");
        }
        log.info("领取失败");
        return Result.fail("领取失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchReceiveCoupons(List<UserCoupon> userCoupons) {
        if (userCoupons == null || userCoupons.isEmpty()) {
            return false;
        }

        LocalDateTime now = LocalDateTime.now();
        for (UserCoupon coupon : userCoupons) {
            // 设置默认值
            coupon.setGetTime(now);
            coupon.setStatus((short) 1);
            coupon.setCreatedTime(now);
            coupon.setUpdatedTime(now);
        }

        return userCouponMapper.batchInsert(userCoupons) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean useCoupon(Long id, String orderNo) {
        if (id == null || orderNo == null || orderNo.trim().isEmpty()) {
            return false;
        }

        // 检查优惠券状态
        UserCoupon userCoupon = getById(id);
        if (userCoupon == null || userCoupon.getStatus() != 1) {
            return false;
        }

        // 检查优惠券是否过期
        Coupon coupon = couponService.getById(userCoupon.getCouponId());
        if (coupon == null || coupon.getEndTime().isBefore(LocalDateTime.now())) {
            return false;
        }

        // 更新优惠券状态为已使用
        LocalDateTime now = LocalDateTime.now();
        return userCouponMapper.updateStatus(id, (short) 0, now, orderNo) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelUseCoupon(String orderNo) {
        if (orderNo == null || orderNo.trim().isEmpty()) {
            return false;
        }

        // 查询订单使用的优惠券
        UserCoupon userCoupon = getByOrderNo(orderNo);
        if (userCoupon == null || userCoupon.getStatus() != 0) {
            return false;
        }

        // 更新优惠券状态为未使用
        return userCouponMapper.updateStatus(userCoupon.getId(), (short) 1, null, null) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void markExpiredCoupons() {
        LocalDateTime now = LocalDateTime.now();
        // 查询所有过期未使用的优惠券
        List<UserCoupon> expiredCoupons = userCouponMapper.selectExpiredUnusedCoupons(now);

        if (expiredCoupons != null && !expiredCoupons.isEmpty()) {
// 提取ID列表
            List<Long> ids = expiredCoupons.stream()
                    .map(UserCoupon::getId)
                    .collect(java.util.stream.Collectors.toList());

            // 批量更新为过期状态
            userCouponMapper.batchUpdateExpiredStatus(ids, now);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Long id) {
        if (id == null) {
            return false;
        }
        return userCouponMapper.deleteById(id) > 0;
    }

    @Override
    public boolean checkUserHasCoupon(Long userId, Long couponId) {
        if (userId == null || couponId == null){
            return false;
        }
        return userCouponMapper.selectByUserIdAndCouponIdAndStatus(userId, couponId, (short)1) != null;
    }

    @Override
    public Result<?> checkCouponScope(Long teacherId) {
        Course course = new Course();
        course.setTeacherId(teacherId);
        List<Course> courses = courseMapper.selectByCondition(course);
        if (courses == null || courses.isEmpty()) {
            return Result.fail("该老师没有课程");
        }
        return Result.success(courses);
    }
}
